<?php

namespace app\modules\Product\models;

use Yii;
use app\modules\Cruise\models\Cruise;
use app\modules\Cruise\models\Image;
use app\modules\Cruise\models\Room;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderRoom;
use app\modules\Order\models\OrderRoomCustomer;
use app\modules\Order\models\OrderPriceType;
use app\modules\Finance\models\FinanceOrder;
use yii\db\Query;
/**
 * This is the model class for table "product".
 *
 * @property integer $id
 * @property integer $cruise_id
 * @property string $code
 * @property string $go_time
 * @property string $return_time
 * @property integer $day
 * @property integer $from_city
 * @property integer $to_city
 * @property string $name
 * @property integer $line
 * @property string $cost
 * @property string $visa
 * @property integer $status
 * @property integer $user_id
 * @property string $created_at
 * @property string $updated_at
 */
class Product extends \yii\db\ActiveRecord
{
    public  $begin_go_time;
    public  $end_go_time;
    public  $supplier_id;
    public  $min_price;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'product';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cruise_id'], 'required'],
            [['cruise_id', 'day', 'from_city', 'to_city', 'line', 'status', 'user_id', 'type', 'date_limit', 'stock','go_city','return_city'], 'integer'],
            [['go_time', 'return_time', 'created_at', 'updated_at', 'trip','trip_img'], 'safe'],
            [['cost', 'visa', 'nocost', 'cancel', 'discount', 'signup', 'land', 'expense', 'room_remark','special','important','safe_1','safe_2','safe_3','cross_talk'], 'string'],
            [['code'], 'string', 'max' => 64],
            [['sale'], 'string', 'max' => 255],
            [['name', 'trip_sort'], 'string', 'max' => 128],
        ];
    }


    // 保存前处理
    public function beforeSave($insert) {//{{{
        if($insert){
            $this->created_at = date("Y-m-d H:i:s");
            $this->user_id    = Yii::$app->user->id;
            // trip_sort todo
        }
            
        $day = (strtotime($this->return_time) - strtotime($this->go_time))/  (60 * 60 * 24); 
        if(!empty($day)){
            $this->day = $day+1;
            $sort = explode(',', $this->trip_sort);
            // 日期修改 行程中的项数排序跟随变化
            if(count($sort) != $this->day){
               $trip_sort = range(0, $day);
               $this->trip_sort = implode(',', $trip_sort);
            }
        }
        
        if($this->cruise_id){
			if(empty($this->code) && $this->go_time){
            	$cruise = Cruise::findOne($this->cruise_id);
            	$code   = sprintf("%s%s", $cruise->code,  date('Ymd', strtotime($this->go_time))); 
            	$this->code = $code;
			}
        }

        return parent::beforeSave($insert);
    }//}}}

    // 保存后执行
	public function afterSave($insert, $changedAttributes){//{{{

		parent::afterSave($insert, $changedAttributes);

		if($insert) {
			// 日志
			$desc = "创建新航线";
			Yii::$app->logs->info($this->id, 1, $desc, '' , 2);
		}else{
			if(isset($changedAttributes['date_limit'])) {

				$desc = sprintf("设置占位期限  %s", $this->date_limit);
				Yii::$app->logs->info($this->id, 1, $desc, '' , 2);
			}

			if(isset($changedAttributes['rooms'])) {
				$desc = sprintf("设置舱房价格");
				Yii::$app->logs->info($this->id, 1, $desc, '' , 2);
			}
		}
	}//}}}



    //  获取对应供应商   
    public function getCruise(){
        return $this->hasOne(Cruise::className(), ['id' => 'cruise_id']);
    }

    // 获取对应图片
    public function getImage(){
        return  $this->hasOne(Image::className(),['product_id'=>'cruise_id'])->andWhere(['image.type'=>1,'image.status'=>1])->orderby('image.cover desc');
    }

    // 获取所有房型 // 设置排序
    public function getAllRoom(){
        return $this->hasMany(Room::className(), ['cruise_id' => 'cruise_id'])->onCondition(['status'=>1])->orderBy('room.sort');
    }

    // 获取该线路对应的所有舱房
    public function getProductRoom(){
        return $this->hasMany(ProductRoom::className(), ['product_id' => 'id']);
    }
    //获取该线路对应的所有舱房数量
    public function getAllRoomNum(){
		if(Yii::$app->user->can('order_all')){
        	return $this->hasMany(OrderRoom::className(), ['product_id' => 'id'])->onCondition(['status'=>1])->count();
		}else{
        	return $this->hasMany(OrderRoom::className(), ['product_id' => 'id'])->onCondition(['status'=>1, 'user_id'=>Yii::$app->user->identity->id])->count();
		}
    }


	/** 订单信息 ------------------- */

    //获取该线路对应的所有订单  有效订单
    public function getAllOrder(){
        return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['<', 'status',10])->orderBy("relation");
    }

    //按指定条件 获取该线路对应的所有订单  有效订单
    //public function getAllOrderCondition($username, $priceType, $status){
    //    return $this->hasMany(Order::className(), ['product_id' => 'id'])
	//						->onCondition(['<', 'status',10])
	//						->orderBy("relation");
    //}

    //获取该线路对应的所有订单总数  有效订单
    public function getAllOrderNum(){
		if(Yii::$app->user->can('order_all')){
        	return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['<', 'status',10])->count();
		}else{
        	return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4], 'member_id'=>Yii::$app->user->identity->id])->count();
		}
    }

    //获取该线路对应的已付款订单总数  有效订单
    public function getPayOrderNum(){
        if(Yii::$app->user->can('order_all')){
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[3,4]])->count();
        }else{
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[3,4], 'member_id'=>Yii::$app->user->identity->id])->count();
        }
    }


    //获取该线路对应的已付款订单  有效订单
    public function getPayOrder(){
        if(Yii::$app->user->can('order_all')){
            //return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[3,4]])->all();
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['order.status'=>[3,4]]);
        }else{
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['order.status'=>[3,4], 'order.member_id'=>Yii::$app->user->identity->id]);
        }
    }


    //获取该线路对应的 占位  已付款 确认订单  有效订单
    public function getPayOrderAll(){
        if(Yii::$app->user->can('order_all')){
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['order.status'=>[1,2,3,4]]); //,4
        }else{
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['order.status'=>[1,2,3,4], 'order.member_id'=>Yii::$app->user->identity->id]); //,4
        }
    }

    //获取该线路对应的 占位  已付款 确认订单  有效订单  付款-取消 定金-取消 
    public function getNewPayOrderAll(){
        if(Yii::$app->user->can('order_all')){
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['order.status'=>[1,2,3,4,11,13]]); //,4
        }else{
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['order.status'=>[1,2,3,4,11,13], 'order.member_id'=>Yii::$app->user->identity->id]); //,4
        }
    }


	// 获取该线路对应所有订单的总人数
	public function getAllCustomerNum(){//{{{

		if(Yii::$app->user->can('order_all')){
        	$data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['<', 'status',10])->all();
		}else{
        	$data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4], 'member_id'=>Yii::$app->user->identity->id])->all();
		}
			
		$ids = yii\helpers\ArrayHelper::map($data , 'id', 'id');
		$num = OrderRoomCustomer::find()->where(['order_id'=>$ids, 'status'=>1])->count();
		return $num;
	}//}}}

    //获取该线路对应的所有有效订单的金额总和 (包含 付款取消的订单)
    public function getAllOrderPrice(){

		if(Yii::$app->user->can('order_all')){

        	return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4] ])->sum('price');
		}else{
		
        	return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4], 'member_id'=>Yii::$app->user->identity->id])->sum('price');
		}
    }


	/*** 库存信息 ***/
	// 航线对应的库存总数  母港
    public function getStockAll(){
        return $this->hasMany(ProductRoom::className(), ['product_id' => 'id'])->sum('num');
    }

	// 航线对应的库存总数  海外 
    public function getStockAll2(){
		$num = 0;

		if($this->rooms){
			$rooms = json_decode($this->rooms, true);
			foreach($rooms as $room){
				if(isset($room['num']) && is_numeric($room['num'])){
					$num += $room['num'];	
				}
			}
		}
		return $num;
    }

	// 航线售出库存数量 (占位 + 售出 + 已提交)
	public function getSurplusStock(){
        return $this->hasMany(OrderRoom::className(), ['product_id' => 'id'])->onCondition(['order_room.status'=>1, 'order_room.stock'=>1])->count();
	}

	// 航线订单对应的所有舱房数量
    public function stockSale($ids){
		return OrderRoom::find()->where(['order_id'=>$ids,'status'=>1, 'stock'=>1])->count();
    }

	// 航线指定房型的库存数量 room_id = product_room->id
	public function getStockRoom($room_id){
		if($this->stock == 1){ //  母港

        	return $this->hasMany(ProductRoom::className(), ['product_id' => 'id'])->onCondition(['id'=>$room_id]);
		}elseif($this->stock == 2){ // 海外

			$rooms = empty($this->rooms) ? [] : json_decode($this->rooms, true);
			return isset($rooms[$room_id]) ? $rooms[$room_id] : [];
		}
	}

	// 航线指定房型的库存销售数量 room_id = product_room->id
	public function getSellStockRoom($room_id){

        return $this->hasMany(OrderRoom::className(), ['product_id' => 'id'])->onCondition(['room_id'=>$room_id, 'status'=>1, 'stock'=>1])->count();
	}

	// 航线指定房型库存剩余数量
	public function getSurplusRoom($room_id){//{{{
		if($this->stock == 1){ // 标准 
			// 获取 product_room 
			$room = ProductRoom::findOne($room_id);

			$total = $room->num;

			$sell = OrderRoom::find()->where(['product_id'=>$this->id, 'room_id'=>$room_id, 'status'=>1, 'stock'=>1])->count();
			return $total - $sell;

		}elseif($this->stock == 2){ // 自定义

			$rooms = empty($this->rooms) ? [] : json_decode($this->rooms, true);

			$total = isset($rooms[$room_id]) ? $rooms[$room_id]['num'] : 0;

			$sell = OrderRoom::find()->where(['product_id'=>$this->id, 'room_id'=>$room_id, 'status'=>1, 'stock'=>1])->count();

			$num = (($total-$sell ) < 0)  ? 0 : ($total-$sell );

			return $num;
		}
	}//}}}


	// 航线库存的整体情况
	public function getStockDetail(){//{{{
		if($this->stock == 1){ //  母港 标准库存格式
			
        	return $this->hasMany(ProductRoom::className(), ['product_id' => 'id']);// ->orderBy('num desc')
		}elseif($this->stock == 2){ // 海外 自定义库存格式

			$rooms = empty($this->rooms) ? [] : json_decode($this->rooms, true);

			//yii\helpers\ArrayHelper::multisort($rooms, 'num', SORT_DESC);
			
			//print_r($rooms);exit;
			return $rooms;
		}
	}//}}}

	// 获取航期附加费类型
	public function getPriceType(){//{{{
		
        return $this->hasMany(OrderPriceType::className(), ['product_id' => 'id'])->onCondition(['status'=>1]);
	}//}}}


    /******航线获取最低价格*****/
    public function getMinPrice(){
        if($this->stock == 1){

            return $this->hasMany(ProductRoom::className(),['product_id' => 'id'])->onCondition(['show'=>1])->onCondition(['<=','people',2])->onCondition(['>','price',0])->min("price");

        }elseif($this->stock == 2){

            $all = [];
            $rooms = empty($this->rooms) ? [] : json_decode($this->rooms, true);
            foreach($rooms as $m){
                if(!empty($m['price'])){
                   $all[] = $m['price'];  
                }
            }
            $minPrice = empty($all) ? 0 : min($all); 
            return $minPrice;
        }
    }

    /*********获得各订单状态数量***************/
    public function getOrderStatus(){
        $data = [];
        foreach(\yii::$app->params['order_status'] as $key=>$val){
            $data[$key] = $this->hasMany(Order::className(),['product_id'=>'id'])->onCondition(['status'=>$key])->count();
        }
        return  $data;
    }

    /*********每个销售者销售订单详情************/
    public function getSellOrderNum(){
        $all = $this->hasMany(Order::className(),['product_id'=>'id'])->onCondition(['status'=>[1,2,3,4]])->addGroupBy('member_id')->all();
        $data = [];
        if(!empty($all)){
            foreach($all as $key=>$model){
                $data[$key]['name'] = $model->member->profile->name;
                $data[$key]['num'] = $this->hasMany(Order::className(),['product_id'=>'id'])->onCondition(['status'=>[1,2,3,4],'member_id'=>$model->member_id])->count();
                $data[$key]['price'] = $this->hasMany(Order::className(),['product_id'=>'id'])->onCondition(['status'=>[1,2,3,4],'member_id'=>$model->member_id])->sum("price");
            }
        }
        return $data;
    }

    /*********获取各状态订单的房间数量******/
    public function getStatusOrderRoom(){
        $data = [1=>0,2=>0,3=>0,4=>0,100=>0];
        $all = $this->hasMany(Order::className(),['product_id'=>'id'])->onCondition(['status'=>[1,2,3,4]])->all();
        if(!empty($all)){
            foreach($all as $model){
                if($model->status == 1){
                    $data[1] += $model->roomNum;
                }else if($model->status == 2){
                    $data[2] += $model->roomNum;
                }else if($model->status == 3){
                    $data[3] += $model->roomNum;
                }else if($model->status == 4){
                    $data[4] += $model->roomNum;
                }
            }
        }
        if($this->stock == 1){
            $data[100] = $this->getStockAll()-($data[1]+$data[2]+$data[3]+$data[4]);
        }else if($this->stock == 2){
            $data[100] = $this->getStockAll2()-($data[1]+$data[2]+$data[3]+$data[4]);
        }
        
        return $data;
    }
    /*********获取各状态订单的数量******/
    public function getStatusOrderNum(){
        $data = [1=>0,2=>0,3=>0,4=>0,100=>0];
        $all = $this->hasMany(Order::className(),['product_id'=>'id'])->onCondition(['status'=>[1,2,3,4]])->all();
        if(!empty($all)){
            foreach($all as $model){
                if($model->status == 1){
                    $data[1] += 1;
                }else if($model->status == 2){
                    $data[2] += 1;
                }else if($model->status == 3){
                    $data[3] += 1;
                }else if($model->status == 4){
                    $data[4] += 1;
                }
            }
        }
        $data[100] = $data[1]+$data[2]+$data[3]+$data[4];
        return $data;
    }
    //获取该线路对应所有订单的总人数
    public function getCustomerNums($source){

        if($source == 0){
          $data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4]])->all();    
        }else if($source == 1){
          $data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition([ 'status'=>[1,2,3,4],'source'=>1])->all();   
        }else if($source == 2){
          $data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4],'source'=>2])->all();   
        }
        
        $ids = yii\helpers\ArrayHelper::map($data , 'id', 'id');
        $num = OrderRoomCustomer::find()->where(['order_id'=>$ids,'status'=>1])->count();
        return $num;
    }

    //获取该线路对应订单的总人数
    public function getStatusCustomerNums($status){

        if($status == 1){
          $data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>1])->all();    
        }else if($status == 2){
          $data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition([ 'status'=>2])->all();   
        }else if($status == 3){
          $data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition([ 'status'=>3])->all();   
        }else if($status == 4){
          $data = $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>4])->all();   
        }
        
        $ids = yii\helpers\ArrayHelper::map($data , 'id', 'id');
        $num = OrderRoomCustomer::find()->where(['order_id'=>$ids])->count();
        return $num;
    }

    //获取该线路对应的所有有效订单的金额总和 (包含 付款取消的订单)
    public function getSourceOrderPrice($source){

        if($source == 0){
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4,11,12]])->sum('price');
        }else if($source == 1){
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4,11,12],'source'=>1])->sum('price');
        }else if($source == 2){
            return $this->hasMany(Order::className(), ['product_id' => 'id'])->onCondition(['status'=>[1,2,3,4,11,12],'source'=>2])->sum('price');
       }
    }

	/** 获取财务审批通过总金额 */
	public function getFinanceSuccess(){//{{{
		// $query = new Query;

		// $query->select('sum(finance_order.price) total')->from('finance')
		// 	  ->leftJoin('finance_order', 'finance_order.finance_id = finance.id');

		// $query->andWhere(['finance_order.product_id'=>$this->id]);
		// $query->andWhere(['finance.status'=>3]);


		// if(! Yii::$app->user->can('order_all')){

  //       	$query->andWhere(['finance.user_id'=>Yii::$app->user->identity->id]);
		// }

		// $query->all();
		// $command = $query->createCommand();

		// $ret = $command->queryOne();

		// return $ret['total'];

        //收款金额
        $query = new Query;
        $query->select('sum(finance_order.price) total')->from('finance_order')
              ->leftJoin('finance','finance_order.finance_id = finance.id')  
              ->leftJoin('order','finance_order.order_id = order.id');
        $query->andWhere(['finance_order.product_id'=>$this->id]);
        $query->andWhere(['finance.type'=>1]);
        $query->andWhere(['finance.status'=>3]);   

        if(! Yii::$app->user->can('order_all')){
            $query->andWhere(['order.user_id'=>Yii::$app->user->identity->id]);
        }

        $query->all();
        $command = $query->createCommand();

        $ret = $command->queryOne();

        $price = $ret['total'];

        //退款金额
        $query2 = new Query;
        $query2->select('sum(finance_order.price) total')->from('finance_order')
              ->leftJoin('finance','finance_order.finance_id = finance.id')  
              ->leftJoin('order','finance_order.order_id = order.id');
        $query2->andWhere(['finance_order.product_id'=>$this->id]);
        $query2->andWhere(['finance.type'=>3]);
        $query2->andWhere(['finance.status'=>3]);   

        if(! Yii::$app->user->can('order_all')){
            $query2->andWhere(['order.user_id'=>Yii::$app->user->identity->id]);
        }

        $query2->all();
        $command2 = $query2->createCommand();

        $ret2 = $command2->queryOne();

        $price2 = $ret2['total'];
        
        $price_1 = $price - $price2;
        
        return sprintf("%.2f", $price_1); 


	}//}}}}

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'cruise_id' => Yii::t('app.cruise', 'Cruise ID'),
            'code' => Yii::t('app.cruise', 'Code'),
            'go_time' => Yii::t('app.cruise', 'Go Time'),
            'return_time' => Yii::t('app.cruise', 'Return Time'),
            'day' => Yii::t('app.cruise', 'Day'),
            'from_city' => Yii::t('app.cruise', 'From City'),
            'to_city' => Yii::t('app.cruise', 'To City'),
            'name' => Yii::t('app.cruise', 'Name'),
            'line' => Yii::t('app.cruise', 'Line'),
            'cost' => Yii::t('app.cruise', 'Cost'),
            'visa' => Yii::t('app.cruise', 'Visa'),
            'status' => Yii::t('app', 'Status'),
            'user_id' => Yii::t('app', 'User ID'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
            'trip' => Yii::t('app', 'Trip'),
            'day' => Yii::t('app.cruise', 'Day'),
            'nocost' => Yii::t('app.cruise', 'Nocost'),
            'cancel' => Yii::t('app.cruise', 'Cancel'),
            'discount' => Yii::t('app.cruise', 'Discount'),
            'signup' => Yii::t('app.cruise', 'Signup'),
            'land' => Yii::t('app.cruise', 'Land'),
            'expense' => Yii::t('app.cruise', 'Expense'),
            'type' => Yii::t('app.cruise', 'Type'),
            'room_remark' => Yii::t('app.cruise', 'Room Remark'),
            'sale' => Yii::t('app.cruise', 'Sale'),
            'date_limit' => Yii::t('app.cruise', 'Date Limit'),
            'stock' => Yii::t('app.cruise', 'Stock'),
            'begin_go_time' => '',
            'end_go_time' => '',
            'trip_img' => Yii::t('app.cruise', 'Trip Img'),
            'min_price' => '',
            'go_city' => Yii::t('app.cruise', '上船城市'),
            'return_city' => Yii::t('app.cruise', '下船城市'),
            'special' => Yii::t('app.cruise', '产品特色'),
            'important' => Yii::t('app.cruise', '重要提示'),
            'cross_talk' => Yii::t('app.cruise', '相声价格'),
            'safe_1' => Yii::t('app.cruise', '行前解约风险提醒'),
            'safe_2' => Yii::t('app.cruise', '人身财产安全警示'),
            'safe_3' => Yii::t('app.cruise', '第三方责任告知'),
            
        ];
    }
}
